const express=require('express')
const multer=require('multer')
const mysql=require('mysql2/promise')
const path=require('path')
const app=express()
app.use(require('cors')())
// app.use(express.static('uploads'))

const storage=multer.diskStorage({
  destination:(req,file,cb)=>{cb(null,'uploads/')},
  filename:(req,file,cb)=>{
    const uniqueSuffix=Date.now()+'-'+Math.round(Math.random()*1E9)
    cb(null,file.fieldname+'-'+uniqueSuffix+path.extname(file.originalname))
  }
})
const upload=multer({storage})
const db=mysql.createPool({
  host:'localhost',
  user:'root',
  password:'root123',
  database:'demo'
})
app.post('/upload',upload.single('img'),async(req,res)=>{
  try {
    if (!req.file) {
      return res.status(400).json({error:'未选择图片'})
    }
  const{filename,path}=req.file
  const sql='insert into images(image_path,image_name)values(?,?)'
  const[result]=await db.execute(sql,[filename,path])
  res.send({
    message:'上传成功，路径已存入数据库',
    imageId:result.insertId,
    path
  })
  } catch (error) {
    console.error('错误',error)
    res.status(500).send('服务器错误')
  }
  
})
app.get('/api/images',async(req,res)=>{
  try {
    const[rows]=await db.execute('select id,image_path from images')
    res.send(rows)
  } catch (error) {
    res.status(500).send('查询失败')
  }
})

app.listen(3000,()=>{console.log('server is running at http://localhost:3000/upload');})